package edu.umn.contactviewer;

import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import edu.umn.contactviewer.models.Contact;
import edu.umn.contactviewer.webservice.WebServiceClient;

/** Displays a list of contacts.
 *
 */
public class ContactListActivity extends ListActivity implements View.OnClickListener {
	
	ArrayList<Contact> contacts;
	private int index;
	
	class GetAllContactsTask extends AsyncTask<URL, Integer, ArrayList<Contact>> {

    	@Override
    	protected ArrayList<Contact> doInBackground(URL... arg0) {
    		return WebServiceClient.getAllContacts();
    	}
    	
    	protected void onPostExecute( ArrayList<Contact> webServiceContacts ) {
    		super.onPostExecute( webServiceContacts );
    		contacts = webServiceContacts;
    		displayContacts();
    	}
    }
	
	class DeleteTask extends AsyncTask<String, Integer, Integer> {

    	@Override
    	protected Integer doInBackground(String... _id) {
    		return WebServiceClient.deleteContact(_id[0]);
    	}
    	
    	protected void onPostExecute( Integer responseStatus ) {
    		super.onPostExecute(null);
    		
    		if( responseStatus == 200 ) {
    			contacts.remove( index );
    			displayContacts();
    		}
    	}
    }
	
	private void displayContacts() {
		Collections.sort(contacts);

        // initialize the list view
        setListAdapter(new ContactAdapter(this, R.layout.list_item, contacts));
        ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        
        // handle the item click events
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("contact", (Contact) getListAdapter().getItem(position));
                Intent intent = new Intent();
                intent.setClass(ContactListActivity.this, ContactInfoActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
                }
            }
        );

        findViewById(R.id.toolbar_right_button).setOnClickListener(this);
        findViewById(R.id.toolbar_back_button).setOnClickListener(this);
        
        registerForContextMenu( lv );
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list);
        ToolbarConfig toolbarConfig = new ToolbarConfig(this, "Contacts");
        toolbarConfig.getToolbarRightButton().setText("Add");

        Context ctxt = this.getBaseContext();

        new GetAllContactsTask().execute();
    }

    public void onClick(View view) {
        if (view.getId() == R.id.toolbar_right_button) {
            Bundle bundle = new Bundle();
            bundle.putSerializable("contact", new Contact());
            Intent intent = new Intent();
            intent.setClass(ContactListActivity.this, ContactEditActivity.class);
            intent.putExtras(bundle);
            startActivity(intent);
        }
        else if (view.getId() == R.id.toolbar_back_button) {
            Intent intent = new Intent(this, HomeActivity.class);
            startActivity(intent);
            overridePendingTransition( R.anim.slide_in_right, R.anim.slide_out_right );
        }
    }
    
    public void onCreateContextMenu(ContextMenu menu, View v,
		            ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.context_menu, menu);
		}
    
    public boolean onContextItemSelected(MenuItem item) {
    	Context ctxt = this.getBaseContext();
    	
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

        index = (int)info.id;
        Contact contact = contacts.get( index );

        new DeleteTask().execute(contact.get_id());

        return false;
    }

    /* We need to provide a custom adapter in order to use a custom list item view.
     */
    public class ContactAdapter extends ArrayAdapter<Contact> {
    
        public ContactAdapter(Context context, int textViewResourceId, List<Contact> objects) {
            super(context, textViewResourceId, objects);
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = getLayoutInflater();
            View item = inflater.inflate(R.layout.list_item, parent, false);
            
            Contact contact = getItem(position);
            ((TextView)item.findViewById(R.id.item_name)).setText(contact.getName());
            ((TextView)item.findViewById(R.id.item_title)).setText(contact.getTitle() + " ");
            ((TextView)item.findViewById(R.id.item_phone)).setText(contact.getPhone());
            
            return item;
        }
    }
    
}